//
//  LimitInputTextView.m
//  CKApp
//
//  Created by CC on 2020/9/12.
//  Copyright © 2020 This Moment. All rights reserved.
//

#import "LimitInputTextView.h"
#import "LcFoundation.h"

@implementation LimitInputTextView

- (void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)awakeFromNib {
  [super awakeFromNib];
  [self setUp];
}

- (void)setUp {
  self.maxLimitLength = 1000;
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChangeAction:) name:UITextViewTextDidChangeNotification object:self];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditingAction:) name:UITextViewTextDidEndEditingNotification object:self];
}

- (void)textDidChangeAction:(NSNotification*)notification {
  if ([notification.object isKindOfClass:[UITextView class]]) {
    UITextView* textView = (UITextView*)notification.object;
    if (textView == self && [self needCheckInputingLanguage]) {
      [self subTextViewContentToLimitLength:self.text];
    }
  }
  [self setNeedsDisplay];
  [self setNeedsLayout];
  if (self.limitInputDelegate && [self.limitInputDelegate respondsToSelector:@selector(textDidChangeAction:)]) {
    [self.limitInputDelegate textDidChangeAction:self];
  }
}

- (void)textDidEndEditingAction:(NSNotification*)notification {
  if ([notification.object isKindOfClass:[UITextView class]]) {
    UITextView* textView = (UITextView*)notification.object;
    if (textView == self) {
      [self scrollToCorrectPosition];
    }
  }
  if (self.limitInputDelegate && [self.limitInputDelegate respondsToSelector:@selector(textDidEndEditingAction:)]) {
    [self.limitInputDelegate textDidEndEditingAction:self];
  }
}

- (void)scrollToCorrectPosition {
  if (self.isFirstResponder) {
    [self scrollRangeToVisible:NSMakeRange(-1, 0)];
  } else {
    [self scrollRangeToVisible:NSMakeRange(0, 0)];
  }
}

- (void)subTextViewContentToLimitLength:(NSString*)content {
  NSRange selectedRange = self.selectedRange;
  if (content.length > self.maxLimitLength) {
    self.text = [content substringToIndex:self.maxLimitLength];
    if (selectedRange.location < self.maxLimitLength) {
      self.selectedRange = selectedRange;
    }
  }
}


@end
